<?php
/**
 * @description 微信auth2.0获取openid
 * @Author: eecjimmy
 * @CreateTime: 14-8-12 下午7:11
 */

namespace Home\Controller;


use Think\Controller;

class WeixinController extends Controller
{
    public $appid;
    public $secret;

    public function _initialize()
    {
        $this->appid = 'wx2c626cc4aa650330';
        $this->secret = '918a6d9c3860d568def99ffcaf750e71';
    }

    public function auth()
    {
        $redirect_uri = urlencode('http://huamu.cqcaitou.com/index.php?s=Home/Weixin/auth_reponse');
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appid . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        redirect($url);
    }

    public function auth_reponse()
    {
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->secret.'&code='.$_GET['code'] . '&grant_type=authorization_code';
        $result = file_get_contents($url);
        $result = json_decode($result, true);
        $urls = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=".$this->appid."&grant_type=refresh_token&refresh_token=".$result['refresh_token']."";
        $result = file_get_contents($urls);
        $result = json_decode($result, true);
        $urls = "https://api.weixin.qq.com/sns/userinfo?access_token=".$result['access_token']."&openid=".$result['openid']."&lang=zh_CN";
        $result = file_get_contents($urls);
        $result = json_decode($result, true);
        $openid = $result['openid'];
        if ($openid) {
            $_SESSION['wx_user'] = $result;
        }
        redirect(U('Index/index'));
    }
} 